#include "login.h"
#include "ui_login.h"
#include "widget.h"    // 主界面头文件
#include "register.h"  // 注册界面头文件
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QCryptographicHash>
#include <QFileInfo>
#include <QUdpSocket>
#include <QHostAddress>

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);

    // 初始化UDP套接字
    udpSocket = new QUdpSocket(this);

    // 初始化设置
    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
    setWindowTitle("登录界面");
    setFixedSize(400, 300);

    // 信号连接
    connect(ui->pushButton, &QPushButton::clicked, this, &Login::onRegisterClicked);
    connect(ui->pushButton_2, &QPushButton::clicked, this, &Login::onLoginClicked);
    connect(udpSocket, &QUdpSocket::readyRead, this, &Login::handleServerResponse);
}

Login::~Login()
{
    delete ui;
}

void Login::onLoginClicked()
{
    QString username = ui->lineEdit->text().trimmed();
    QString password = ui->lineEdit_2->text();

    // 输入验证
    if(username.isEmpty() || password.isEmpty()){
        QMessageBox::warning(this, "警告", "请输入用户名和密码");
        return;
    }

    // 密码加密
    QString SALT = "diwu";
    QString encrypted = md5Hash(password + SALT);

    // 构建登录请求
    QString request = "L " + username + " " + encrypted;

    // 发送给服务器
    udpSocket->writeDatagram(request.toUtf8(),
                           QHostAddress("192.168.54.46"), // 服务器IP
                           6666); // 服务器端口
}

void Login::onRegisterClicked()
{
    // 显示注册界面
    Register *reg = new Register();
    reg->setAttribute(Qt::WA_DeleteOnClose); // 自动释放内存
    reg->show();
}

QString Login::md5Hash(const QString &password)
{
    return QCryptographicHash::hash(
        password.toUtf8(),
        QCryptographicHash::Md5
    ).toHex();
}

void Login::handleServerResponse()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray response;
        response.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(response.data(), response.size(), &sender, &senderPort);

        if (response == "LOK") {
            // 进入主界面
            Widget *mainWin = new Widget();
            mainWin->show();
            this->close();
        } else {
            QMessageBox::critical(this, "错误", "登录失败: " + response);
            ui->lineEdit_2->clear();
        }
    }
}
